public class InternTest {
    public static void main(String[] args) {
        // 测试字符串常量池的基本功能
        System.out.println("=== String常量池测试 ===");
        
        // 1. 字面量创建的字符串会直接进入常量池
        String str1 = "Hello";
        String str2 = "Hello";
        
        System.out.println("str1 == str2: " + (str1 == str2)); // true
        System.out.println("str1.equals(str2): " + str1.equals(str2)); // true
        
        // 2. new关键字创建的字符串对象在堆中，不在常量池中
        String str3 = new String("Hello");
        String str4 = new String("Hello");
        
        System.out.println("str3 == str4: " + (str3 == str4)); // false
        System.out.println("str3.equals(str4): " + str3.equals(str4)); // true
        System.out.println("str1 == str3: " + (str1 == str3)); // false
        
        // 3. 使用intern()方法将字符串放入常量池
        String str5 = str3.intern();
        
        System.out.println("str1 == str5: " + (str1 == str5)); // true
        System.out.println("str3 == str5: " + (str3 == str5)); // false
        
        // 4. 测试常量池中不存在的字符串
        String str6 = new String("World");
        String str7 = str6.intern();
        String str8 = "World";
        
        System.out.println("str6 == str7: " + (str6 == str7)); // false
        System.out.println("str7 == str8: " + (str7 == str8)); // true
        
        // 5. 字符串拼接与常量池
        String str9 = "Java";
        String str10 = "Java";
        String str11 = str9 + str10; // 运行时确定
        String str12 = "JavaJava"; // 编译时确定，在常量池中
        
        System.out.println("str11 == str12: " + (str11 == str12)); // false
        
        // 6. 使用final变量的字符串拼接
        final String str13 = "Java";
        final String str14 = "Java";
        String str15 = str13 + str14; // 编译时确定
        String str16 = "JavaJava";
        
        System.out.println("str15 == str16: " + (str15 == str16)); // true
        
        // 7. intern()方法的实际应用示例
        String userInput1 = new String("example");
        String userInput2 = new String("example");
        
        // 不使用intern()时，每次都是新对象
        System.out.println("userInput1 == userInput2: " + (userInput1 == userInput2)); // false
        
        // 使用intern()时，会共享常量池中的同一个对象
        String interned1 = userInput1.intern();
        String interned2 = userInput2.intern();
        System.out.println("interned1 == interned2: " + (interned1 == interned2)); // true
    }
}